package com.ruoyi.netty.controller;

import com.ruoyi.netty.storage.DataQueryService;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.dto.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

@RestController
@RequestMapping("/api/data")
@Slf4j
public class DataApiController {

    @Autowired
    private DataQueryService dataQueryService;

    /**
     * 获取设备最近数据
     */
    @GetMapping("/recent/{deviceId}")
    public Mono<ResponseEntity<QueryResult>> getRecentData(
            @PathVariable String deviceId,
            @RequestParam(defaultValue = "6") int hours,
            @RequestParam(defaultValue = "temperature") String measurement) {
        
        log.info("Querying recent data for device: {}, hours: {}", deviceId, hours);
        return Mono.fromCallable(() -> 
            dataQueryService.queryRecentData(measurement, deviceId, hours)
        ).map(ResponseEntity::ok);
    }

    /**
     * 按时间范围查询数据
     */
    @GetMapping("/range/{deviceId}")
    public Mono<ResponseEntity<QueryResult>> getDataByRange(
            @PathVariable String deviceId,
            @RequestParam(required = false) String start,
            @RequestParam(required = false) String end,
            @RequestParam(defaultValue = "temperature") String measurement,
            @RequestParam(defaultValue = "mean") String aggregation,
            @RequestParam(defaultValue = "5m") String interval) {
        
        Instant startTime = start != null ? Instant.parse(start) : 
                Instant.now().minus(24, ChronoUnit.HOURS);
        Instant endTime = end != null ? Instant.parse(end) : Instant.now();
        
        log.info("Querying data for device: {}, from: {} to: {}", deviceId, startTime, endTime);
        return Mono.fromCallable(() -> 
            dataQueryService.queryByTimeRangeAndDevice(
                measurement, deviceId, startTime, endTime, aggregation, interval)
        ).map(ResponseEntity::ok);
    }

    /**
     * 获取设备报警数据
     */
    @GetMapping("/alarms/{deviceId}")
    public Mono<ResponseEntity<QueryResult>> getAlarms(
            @PathVariable String deviceId,
            @RequestParam(defaultValue = "7") int days) {
        
        log.info("Querying alarms for device: {}, days: {}", deviceId, days);
        return Mono.fromCallable(() -> 
            dataQueryService.queryAlarms(deviceId, days)
        ).map(ResponseEntity::ok);
    }
} 